package com.traitswu.websocket.dmxlog.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import java.io.IOException;
import java.util.function.Predicate;

/**
 * Created by xiaoquan on 17-6-16.
 */
public class DmxLogServerEndpoint extends Endpoint {
    private static Logger LOG = LoggerFactory.getLogger(DmxLogServerEndpoint.class);
    private static final String REQUEST_PATH_LOG_NAME = "loggerName";

    private Predicate<String> IS_BLANK = (k) -> k == null || k.trim().length() == 0;


    private DmxLogWebSocketPipe pipe = DmxLogWebSocketPipe.getInstance();


    @Override
    public void onOpen(Session session, EndpointConfig config) {
        try {
            session.getPathParameters().forEach((k, v) -> System.out.println(k + ":" + v));

            String loggerName = session.getPathParameters().get(REQUEST_PATH_LOG_NAME);
            if (IS_BLANK.test(loggerName)) {
                session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Not found logger name"));
                return;
            }
            LOG.debug("Registe session: [logger:{}, session:{}]", loggerName, session.getId());
            pipe.register(loggerName, session);
            session.getBasicRemote().sendText("Server connect success.");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

    }


    @Override
    public void onClose(Session session, CloseReason closeReason) {
        cancelFromPipe(session);
        super.onClose(session, closeReason);
    }

    @Override
    public void onError(Session session, Throwable throwable) {
        cancelFromPipe(session);
        super.onError(session, throwable);
    }

    private void cancelFromPipe(Session session) {
        String loggerName = session.getPathParameters().get(REQUEST_PATH_LOG_NAME);
        if (IS_BLANK.test(loggerName)) {
            pipe.cancel(session);
        } else {
            pipe.cancel(loggerName, session);
        }
        LOG.debug("cancel from pipe: [logger:{}, session:{}]", loggerName, session.getId());

    }


}
